<template>
  <div class="main-container container-limited container-fluid page-holder" v-loading="loading">
    <template v-if="Object.keys(curDoc).length">
      <doc-breadcrumb />
      <template v-if="curDoc.type === 'ProductSnippet'">
        <h2 class="flex align-items-end" :class="{ 'good-resource-text': curDoc.good }">
          <el-tag v-if="curDoc.good" type="danger" size="small" disable-transitions class="m-r-10">
            精
          </el-tag>
          {{ curDoc.title }}
        </h2>
        <p class="flex align-items-center">
          <router-link
            :to="`/users/${curDoc.author.id}`"
            class="link el-link--primary flex align-items-center"
          >
            <el-avatar :src="curDoc.author.avatar" class="s22 m-r-5" />
            {{ curDoc.author.nickname }}
          </router-link>
          <span class="info m-l-16">
            <i class="el-icon-time"></i>
            <timeago2 :date-time="curDoc.created_at" timeago="none" />
          </span>
          <span class="m-l-30">
            <router-link
              :to="`/spaces/${spaceId}/resources-docs-edit/${curDoc.id}`"
              class="link el-link--primary"
              v-text="'编辑'"
            />
            <delete-link
              v-if="isWebAdmin || isSpaceOwner || isSpaceAdmin
               || (isDocAuthor && curSpace.autoAccept)"
              :delete-item="curDoc"
              class="m-l-5"
              @deletedResource="deletedResource"
            />
          </span>
        </p>
        <el-tag v-for="tag in curDoc.tags" :key="tag" size="small">{{ tag }}</el-tag>
        <div v-if="docCatalog.length" class="m-t-10">
          <div @click="catalog = !catalog" class="pointer title">
            <svg-icon icon-name="stream_list" class="s26" />
          </div>
        </div>
        <div ref="box" class="flex m-t-10">
          <template v-if="docCatalog.length">
            <doc-catalog ref="left" :display="catalog" class="shrink-0" />
            <div ref="resize" v-show="catalog" class="resize-line"></div>
          </template>
          <tinymce-editor
            ref="right"
            v-model="curDoc.anchorContent"
            readonly
            class="flex-1 doc-show-editor"
          />
        </div>
        <attaches-list v-if="curDoc.attaches.length" :attaches="curDoc.attaches" />
      </template>
      <template v-if="curDoc.type === 'ProductLocalFile'">
        <edit-title :editing.sync="titleEditing" />
        <p class="flex align-items-center">
          <router-link
            :to="`/users/${curDoc.author.id}`"
            class="link el-link--primary flex align-items-center"
          >
            <el-avatar :src="curDoc.author.avatar" class="s22 m-r-5" />
            {{ curDoc.author.nickname }}
          </router-link>
          <span class="info m-l-16">
          <i class="el-icon-time"></i>
          <timeago2 :date-time="curDoc.created_at" timeago="none" />
        </span>
          <span class="m-l-30">
          <span
            v-if="curUser.id && !titleEditing"
            @click="titleEditing = true"
            class="link el-link--primary m-r-16">
            重命名
          </span>
          <span class="link el-link--primary" @click.stop="download">下载</span>
          <delete-link
            v-if="isWebAdmin || isSpaceOwner || isSpaceAdmin || isDocAuthor"
            :delete-item="curDoc"
            class="m-l-5"
            @deletedResource="deletedResource"
          />
        </span>
        </p>
        <edit-tags class="m-b-10" />
        <template v-if="curDoc.key">
          <yozo-preview :file="curDoc" />
        </template>
      </template>
      <div class="m-t-16 flex flex-wrap">
        <vote-like :doc="curDoc" @voted="setCurDoc" />
        <vote-dislike :doc="curDoc" @voted="setCurDoc" />
        <span class="m-x-16"></span>
        <el-button type="primary" size="mini" icon="el-icon-edit" @click="commenting = !commenting">
          跟帖
        </el-button>
        <vote-collect :doc="curDoc" @voted="setCurDoc" />
        <mark-good-button v-if="isWebAdmin || isSpaceOwner || isSpaceAdmin" class="m-l-30" />
        <w-x-share
          type="ProductFile"
          :id="curDoc.id"
          page="pages/document/index"
          :scene="`${curDoc.space.id}-${curDoc.id}`"
          :share-url="curDoc.wxShare"
          class="m-l-10"
        />
<!--        <a-->
<!--          class="el-button el-button&#45;&#45;success el-button&#45;&#45;mini"-->
<!--          :href="`http://ac.learnerhub.net/search/?space_id=${curDoc.space.id}&doc_id=${curDoc.id}`"-->
<!--          target="_blank"-->
<!--          v-text="'资源查重'"-->
<!--        />-->
      </div>
      <docs-comments :commenting.sync="commenting" />
    </template>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import MixinWidthResize from '@/utils/mixin-width-resize';
import DocBreadcrumb from '@/components/spaces/resources-v2/breadcrumb';
import DocCatalog from '@/views/documents/components/doc-catalog';
import MarkGoodButton from '@/views/documents/components/mark-good-button';
import DocsComments from '@/components/documents-follow-comments';
import VoteLike from '@/views/documents/components/vote-like';
import VoteDislike from '@/views/documents/components/vote-dislike';
import VoteCollect from '@/views/documents/components/vote-collection';
import EditTitle from '@/views/documents/components/edit-title';
import EditTags from '@/views/documents/components/edit-tags';
import YozoPreview from '@/components/yozo-preview';
import WXShare from '@/components/wx-share-code';
import { formatResource } from '../format';
import DeleteLink from '../delete-link';
import AttachesList from './AttachesList';

export default {
  name: 'DocsShow', // 文档show界面
  mixins: [MixinWidthResize],
  components: {
    DocBreadcrumb,
    DocCatalog,
    DeleteLink,
    DocsComments,
    AttachesList,
    EditTitle,
    EditTags,
    YozoPreview,
    WXShare,
    VoteLike,
    VoteDislike,
    VoteCollect,
    MarkGoodButton,
  },
  data() {
    return {
      loading: false,
      catalog: true,
      commenting: false,
      titleEditing: false,
    };
  },
  computed: {
    ...mapState({
      curDoc: 'currentDocument',
      curUser: 'currentUser',
      curSpace: 'currentSpace',
    }),
    ...mapGetters(['isWebAdmin', 'isSpaceOwner', 'isSpaceAdmin', 'isDocAuthor', 'docCatalog']),
    spaceId() { return this.$route.params.spaceId; },
    loadDocParams() {
      return {
        spaceId: this.spaceId,
        docId: this.$route.params.docId,
      };
    },
  },
  created() { this.loadDoc(); },
  destroyed() { this.setCurDoc(); },
  methods: {
    ...mapActions({ setCurDoc: 'setCurrentDocument' }),
    loadDoc() {
      this.loading = true;
      this.$api.spaceResources.show(this.loadDocParams)
        .then((res) => {
          this.setCurDoc(formatResource(res.data));
          this.$nextTick(() => this.dragControllerDiv());
        })
        .catch(() => { this.$router.push(`/spaces/${this.spaceId}/resources`); })
        .then(() => { this.loading = false; });
    },
    // download
    download() {
      this.$api.other.download({ key: this.curDoc.key, curFileId: this.curDoc.id })
        .then((res) => {
          window.open(`${res.data.ufile}?attname=${this.curDoc.title}${res.data.ext}`, '_self');
        })
        .catch(() => {});
    },
    deletedResource() {
      if (window.history.length > 1) this.goBack(); // 当不是从新页面打开本页面时，返回上一页
      else {
        const folderIdTitle = (this.curDoc.parentPath || '').split('/').pop();
        const folderId = folderIdTitle.substring(0, folderIdTitle.indexOf('-'));
        const path = `/spaces/${this.curDoc.space.id}/resources`;
        this.$router.push(folderId ? `${path}/${folderId}` : path);
      }
    },
  },
  watch: {
    loadDocParams() {
      this.setCurDoc();
      this.loadDoc();
    },
  },
};
</script>

<style></style>
